<?php
/**
 * 商户
 * User: chen guang
 * Date: 2017/9/29 9:00
 *
 */

namespace app\admin\Controller;


use think\Db;
use think\Request;
use think\Cache;

class Set extends Common{
	
	/*
	*	构造函数
	*/
	function __construct(){
		parent::__construct();

	}

    /**
     * 首页分类
     */
    public function type(){
        $list = db("index_type")->order("id asc")->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
	/**
    * 首页分类修改
    */
    public function type_edit(){
    	$id = input('id/d');
		if(empty($id)){
			$this->error("非法操作！");
		}
		$detail=array();
		if(request()->isPost()){
			$data['title']=input("title");
			$data['des']=trim(input('des'));
			$file=request()->file('images');
			if($file){
				$info = $file->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
				if($info){
					$data['images']= $info->getSaveName();
				}
			}
			$res=db("index_type")->where("id='$id'")->update($data);
			if($res===false) $this->error("操作失败！");
			$this->success("操作成功！");
		}
		$detail=db("index_type")->where("id='$id'")->find();
		$this->assign("data",$detail);
    	return $this->fetch();
    }
	/**
	 * banner图
	 */
	public function banner(){
		$banner = db('index_banner')->where("id=1") ->find();
		if(request()->isPost()){
			$file=request()->file('images');
			if($file){
				$info = $file->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
				if($info){
					$data['images']= $info->getSaveName();
				}
			}
			$files=request()->file('images_bj');
			if($files){
				$infos = $files->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
				if($infos){
					$data['images_bj']= $infos->getSaveName();
				}
			}
			$data['title'] = input('title');
			$data['des']   = input('des');
			$res = db('index_banner')->where("id=1")->update($data);
			if($res!==false){$this->success('操作成功');}else{$this->error('操作失败');}
		}
		$this -> assign("data",$banner);
		return $this->fetch();
	}

	/*
	 * 版块介绍
	 */
	public function introduce(){
		$list=db("index_introduce")->select();
		$this->assign("list",$list);
		return $this->fetch();
	}

	/*
      * 版块编辑
      */
	public function in_edit(){
		$id = input('id/d');
		if(empty($id)){
			$this->error('非法操作');
		}
		if(request()->isPost()){
			$file=request()->file('images');
			if($file){
				$info = $file->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
				if($info){
					$data['images']= $info->getSaveName();
				}
			}
			$data['title'] = input('title');
			$data['des']   = input('des');
			$res = db('index_introduce')->where("id='$id'")->update($data);
			if($res!==false){$this->success('操作成功');}else{$this->error('操作失败');}
		}
		$introduce = db('index_introduce')->where("id='$id'") ->find();
		$this -> assign("data",$introduce);
		return $this->fetch();
	}

	/*
      * 底部图编辑
      */
	public function foot_images(){
		if(request()->isPost()){
			$file=request()->file('images');
			if($file){
				$info = $file->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
				if($info){
					$data['images']= $info->getSaveName();
				}
			}
			$files=request()->file('images_bj');
			if($files){
				$infos = $files->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
				if($infos){
					$data['images_bj']= $infos->getSaveName();
				}
			}
			$res = db('index_banner')->where("id=2")->update($data);
			if($res!==false){$this->success('操作成功');}else{$this->error('操作失败');}
		}
		$images = db('index_banner')->where("id=2") ->find();
		$this -> assign("data",$images);
		return $this->fetch();
	}
	/**
	 * 关于我们
	 */
	public function about(){
		$about = db('about')->where("id=1") ->find();
		if(request()->isPost()){
			$file=request()->file('images');
			if($file){
				$info = $file->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
				if($info){
					$data['images']= $info->getSaveName();
				}
			}
			$data['title']    = input('title');
			$data['des']      = input('des');
			$data['tel']      = input('tel');
			$data['business'] = input('business');
			$data['product']  = input('product');
			$res = db('about')->where("id=1")->update($data);
			if($res!==false){$this->redirect(url('Set/about'));}else{$this->error('操作失败');}
		}
		$this -> assign("data",$about);
		return $this->fetch();
	}
	/**
	 * 轮播图
	 */
	public function bannerlist(){
		$banner = db('banner');
		$ban = $banner->select();
		$this -> assign("res",$ban);
		return $this->fetch();
	}
	/**
	 * 图片
	 */
	public function start(){
		$banner = db('pic');
		$ban = $banner->select();
		$this -> assign("res",$ban);
		return $this->fetch();
	}

	public function start_edit(){
		$id = input('id');
		if(request()->isPost()){
			$file = request()->file('bnimage');
			if (!empty($file)) {
				$file_size = $file->getFileInfo()->getPathname();
				$size = getimagesize($file_size);
				if(round($size[0]/$size[1],2) != round(720/1280,2)) {
					$this->error("图片比例不对,请上传720*1280比例图片!");
				}
				$info = $file->move(ROOT_PATH . 'public/static/uploads');
				if ($info) {
					$data['image'] = $info->getSaveName();
				} else {
					$this->success($file->getError());
				}
			}
			$bnr = db('pic')->where("id='$id'")->update($data);
			$this->redirect(url('Set/start'));
		}
		$banner=db('pic')->where("id='$id'")->find();
		$this -> assign("banner",$banner);
		return $this->fetch();

	}
	/**
	 * 轮播添加或修改
	 */
	public function banner_edit(){
		$id = input('id');
		$domina = db('web')->field('type')->select();

		foreach($domina as $k=>$v){
			switch ($v['type']) {
				case '1':
					$title = '关于我们';
					break;
				case '2':
					$title = '用户协议';
					break;
				case '3':
					$title = '版权信息';
					break;
				case '4':
					$title = '商户合作';
					break;
				case '5':
					$title = '软件介绍';	
					break;
				case '6':
					$title = '食圈1';	
					break;
				case '7':
					$title = '食圈2';	
					break;
				case '8':
					$title = '食圈3';	
					break;
				case '9':
					$title = '商城1';	
					break;
				case '10':
					$title = '商城2';
					break;
				case '11':
					$title = '商城3';		
					break;
			}

			$domina[$k]['name'] = $title;
			$domina[$k]['url'] = __ROOT__.'/Index/web/index?type='.$v['type'];
		}

		if(request()->isPost()){
			$data['status'] = input('post.status');
			$data['title'] = input('post.title');
			$data['sort'] = input('post.displayorder');
			$data['url'] = input('post.url');
			$data['type'] = input('type/d');
			$file = request()->file('bnimage');

			if (!empty($file)) {
				$file_size = $file->getFileInfo()->getPathname();
				$size = getimagesize($file_size);

	        	if(round($size[0]/$size[1],2) != round(720/360,2)) {
	        		$this->error("图片比例不对,请上传720*360比例图片!");
	        	}


				$info = $file->move(ROOT_PATH . 'public/static/uploads');
				if ($info) {
					$data['pic'] = $info->getSaveName();
				} else {
					$this->success($file->getError());
				}
			} else {
				$data['pic'] = input('bne');
			}
			if($id){
				$bnr = db('banner')->where("id='$id'")->update($data);
			}else{
				$bnr = db('banner')->insert($data);
			}
			$this->redirect(url('Set/bannerlist'));
			//$this->success("操作成功!",url('Set/bannerlist'));
		}
		$banner=db('banner')->where("id='$id'")->find();
		$this -> assign("banner",$banner);
		$this -> assign("domina",$domina);
		return $this->fetch();

	}
	/**
	 * 轮播删除
	 */
	public function banner_del(){
		$bnid = input('id');
		$banner = db('banner');
		$del = $banner->where("id='$bnid'")->delete();
		$this->success("删除成功",url('Set/bannerlist'));
	}

	/**
	*用户背景图
	*/
	public function user_background_image(){
		$id = input('id');
		if(request()->isPost()){
			$file = request()->file('background_image');
			$info = $file->move(ROOT_PATH . 'public/static/uploads');
			if ($info) {
				$data['background_image'] = $info->getSaveName();
			} else {
				$this->success($file->getError());
			}

			if($id){
				$bnr = db('admin_background_image')->where("id='$id'")->update($data);
			}else{
				$bnr = db('admin_background_image')->insert($data);
			}
			$this->redirect(url('Set/user_background_image'));
			//$this->success("操作成功!",url('Set/user_background_image'));
		}

		$background_image = db('admin_background_image')->find();
		$uploads_path = IMG_PATH;
		$this->assign("background_image",$background_image['background_image']);
		$this->assign("uploads_path",$uploads_path);
		$this->assign("id",$background_image['id']);
		return $this->fetch();
	}

	//设置PM数
	public function set_baidu_param(){
		if(request()->isPost()){
			$img_value = input('img_value');

			if(!is_numeric($img_value)){
				$this->error('请填写数字');
			}

			if(empty($img_value))$this->error('请填写图片PM参数');

			$rel = db('interface_value')->where(array('type'=>'1'))->update(array('param'=>$img_value));

			$this->redirect(url('Set/set_baidu_param'));
		}

		$interface_value = db('interface_value')->where(array('type'=>'1'))->find();

		$this->assign('interface_value',$interface_value);
		return $this->fetch();
	}

	//百度图片搜索PM调试
	public function baidu_search_pictures_debugging(){
		$interface_value = db('interface_value')->where(array('type'=>'1'))->find();
		$img_value = input('img_value')?input('img_value'):$interface_value['param'];
		
		$res = array();
		$result_json = '';
		$result = array('status'=>'0','message'=>'请上传文件');
		
        if(request()->isPost()){ 
        	$file = request()->file('pm_image');

        	if($file){
		        $file = $file->getFileInfo()->getPathname();
		        $size = getimagesize($file);
		        if(round($size[0]/$size[1],2) == round(660/490,2)){;
			        $token = $this->getToken();
			        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' . $token;
			        $img = file_get_contents($file);
			        $img = base64_encode($img);
			        $bodys = array(
			            'image' => $img,
			            'top_num' => 5,
			            'filter_threshold'=>$img_value
			        );

			        $result_json = $this->request_post($url, $bodys);
			        $result_json = $this->_format_json($result_json);
			        
			        $res = json_decode($this->request_post($url, $bodys),true);
			        if($res['result_num'] > 0){
			            foreach($res['result'] as &$r){
			                $r['probability'] = (string)round($r['probability'] * 100,2).'%';
			            }
			        }

			        $result = array('status'=>'1');
		    	}else{
		    		$result = array('status'=>'0','message'=>'图片比例不对');
		    	}
	    	}	
		}else{
			$result = array('status'=>'0','message'=>'请上传文件');
		}

		if(empty($res['result'])){
			$res['result'] = array();
		}

		$this->assign('img_value',$img_value);
		$this->assign('result_json',$result_json);
		$this->assign('res',$res['result']);
		$this->assign('result',$result);
		return $this->fetch();
	}

	/**
	* Formats a JSON string for pretty printing
	*
	* @param string $json The JSON to make pretty
	* @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks
	* @return string The prettified output
	*/
	function _format_json($json, $html = false) {
	 $tabcount = 0;
	 $result = '';
	 $inquote = false;
	 $ignorenext = false;
	 if ($html) {
	  $tab = "   ";
	  $newline = "<br/>";
	 } else {
	  $tab = "\t";
	  $newline = "\n";
	 }
	 for($i = 0; $i < strlen($json); $i++) {
	  $char = $json[$i];
	  if ($ignorenext) {
	  $result .= $char;
	  $ignorenext = false;
	  } else {
	  switch($char) {
	   case '{':
	   $tabcount++;
	   $result .= $char . $newline . str_repeat($tab, $tabcount);
	   break;
	   case '}':
	   $tabcount--;
	   $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
	   break;
	   case ',':
	   $result .= $char . $newline . str_repeat($tab, $tabcount);
	   break;
	   case '"':
	   $inquote = !$inquote;
	   $result .= $char;
	   break;
	   case '\\':
	   if ($inquote) $ignorenext = true;
	   $result .= $char;
	   break;
	   default:
	   $result .= $char;
	  }
	  }
	 }
	 return $result;
	}


    /**
     * 获取百度token
     */
    public function getToken(){
        if(!Cache::has('baidu_image_access_token')){
            $url = 'https://aip.baidubce.com/oauth/2.0/token';
            $post_data['grant_type']       = 'client_credentials';
            $post_data['client_id']      = config('baidu.client_id');
            $post_data['client_secret'] = config('baidu.client_secret');
            $o = "";
            foreach ( $post_data as $k => $v )
            {
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);
            $res = json_decode($this->request_post($url, $post_data));
            Cache::set('baidu_image_access_token',$res->access_token,$res->expires_in);
        }
        return Cache::get('baidu_image_access_token');


    }

    /**
     * 发起http post请求(REST API), 并获取REST请求的结果
     * @param string $url
     * @param string $param
     * @return - http response body if succeeds, else false.
     */
    private function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }
}